package com.github.baichuan.web.ui.select;

import com.github.baichuan.mapping.EnumDescription;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

public final class SelectUtils {
    private SelectUtils() {

    }

    public static OptionItem[] options(Class<? extends Enum> clazz) throws IllegalAccessException {
        Set<Field> fields = Arrays.stream(clazz.getDeclaredFields()).filter(x -> x.isEnumConstant())
                .collect(Collectors.toSet());
        OptionItem[] options = new OptionItem[fields.size()];

        for(Field field : fields){
            Enum enumField = (Enum)field.get(null);
            String name = (enumField).name();
            int value = enumField.ordinal();
            EnumDescription description = field.getAnnotation(EnumDescription.class);
            if(description != null) {
                options[value] = OptionItem.of(description.value(), name);
            } else {
                options[value] = OptionItem.of(name, name);
            }
        }
        return options;
    }
}
